﻿using Freshbox2._0.BLL;
using Freshbox2._0.MODEL;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Freshbox2._0.UI.Controllers
{
    public class AdminController : BaseController<admin>
    {
        //
        // GET: /Admin/     
        protected admin CurrentUer
        {
            get { return Session["CurrentUer"] == null ? null : (admin)Session["CurrentUer"]; }
        }

        public override BLL.BaseBll<admin> bll
        {
            get
            {
                return new AdminBll();
            }

        }
        //加载数据列表 查询方法
        public override ActionResult Get(int page, int rows, admin model)
        {
            int count;
            var list = bll.Search(model, x => true, true, x => x.adminId, rows, page, out count).ToList().Select(x => new
            {
                x.adminUsername,
                x.adminPassword,
                x.adminId,
                state = x.state == 1 ? "在职" : "离职",
                x.name,
            }).ToList();
            return Json(new { total = count, rows = list });
        }

        //新增用户 
        [HttpPost]
        public override ActionResult Save(admin model)
        {
            string msg = "";
            int result = 0;
            int jieguo = 1;
            string code = model.adminUsername;
            string pwd = model.adminPassword;

            if (model.adminUsername != "" && model.adminPassword != "")
            {
                var count = bll.Search(x => x.adminUsername == code).Count();
                //判断该用户是否存在
                if (count == 0)
                {
                    model.adminPassword = MD5Encrypt32(pwd);
                    model.areaCode = "11001";

                    model.state = 1;
                    if (bll.Add(model) > 0)
                    {
                        msg = "添加成功";
                        result = 1;
                        jieguo = 1;
                        return Json(new { jieguo = jieguo, state = result, msg = msg });
                    }
                    else
                    {
                        jieguo = 1;
                        msg = "添加失败";
                        return Json(new { jieguo = jieguo, state = result, msg = msg });
                    }
                }
                else
                {
                    jieguo = 0;
                    msg = "该账号已经存在，请重新填写";
                    return Json(new { jieguo = jieguo, state = result, msg = msg });
                }
            }
            else
            {
                jieguo = 0;
                msg = "请填写完整";
                return Json(new { jieguo = jieguo, state = result, msg = msg });
            }
        }

        
        /// <summary>
        /// 修改 密码   
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        public override ActionResult Modify(admin model)
        {
            string msg = "修改失败";
            string state = "false";
            model.adminPassword = MD5Encrypt32(model.adminPassword);
            string code = model.adminUsername;
            string pwd = model.adminPassword;
            model.areaCode = "11001";
           // model.authoritys = 
            model.state = 1;
            if (model.adminUsername != "" && model.adminPassword != "")
            {
                if (bll.Modify(model) > 0)
                {
                    msg = "修改成功";
                    state = "true";
                }
            }
            else
            {
                msg = "请填写完整";
                return Json(new { state = state, msg = msg });
            }

            return Json(new { state = state, msg = msg });
        }

        //禁用用户  修改状态为
        public ActionResult ModifyState(long id)
        {
            string msg = "禁用失败";
            string state = "false";
            ///var oneList = bll.Search(x => x.adminId == id).Select(x => new { x.adminPassword, x.adminUsername, x.state }).ToList();
            admin oneList1 = bll.Search(x => x.adminId == id).FirstOrDefault();
            //admin model = new admin();
            //model = oneList1;
            //model.adminId = id;
            //model.adminUsername = oneList.FirstOrDefault().adminUsername;
            //model.adminPassword = oneList.FirstOrDefault().adminPassword;

            oneList1.state = 0;

            if (bll.Modify(oneList1) > 0)
            {
                msg = "禁用成功";
                state = "true";
            }
            return Json(new { state = state, msg = msg });
        }
        //获取选中的一条数据
        public ActionResult GetOnlyOne(long id)
        {
            return Json(bll.Search(x => x.adminId == id).ToList().Select(x => new { x.adminUsername, x.adminId, x.areaCode,x.adminPassword ,x.authoritys,x.name}).ToList()[0], JsonRequestBehavior.AllowGet);
        }

        //MD5加密方法  32位加密   855444      F269B2C     410  E16 71E C64 5B 6B9A
        public static string MD5Encrypt32(string password)
        {
            string cl = password;
            string pwd = "";
            MD5 md5 = MD5.Create(); //实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("x2");  //x2  32位小写      X2 32位大写    x31位小写
            }
            return pwd;
        }


        
        //  public ActionResult ExportWord()
        //{
        //    CreateAWord();
        //    SetPageHeader("测试创建一个Word文档");
        //    InsertText("这是一个测试文档的内容", 14, WdColor.wdColorGray10, 1, WdParagraphAlignment.wdAlignParagraphLeft);
        //    NewLine();
        //    InsertPicture("C:\\Picture\\a.jpg"); //C:\Picture
        //    InsertTable();
        //    SaveWord("C:\\test.doc");
        //    CloseDocument("C:\\test.doc");
        //    return null;
        //}
        //  /// <summary>
        //  /// Word应用对象  
        //  /// </summary>
        //  private Microsoft.Office.Interop.Word.Application _wordApplication;
        //  /// <summary>
        //  /// word 文件对象 
        //  /// </summary>
        //  /// 
        //  private Microsoft.Office.Interop.Word.Document _wordDocument;

        //  /// <summary>
        //  ///  创建文档  
        //  ///  如果报错：类型“Microsoft.Office.Interop.Word.ApplicationClass”未定义构造函数 ；
        //  ///  解决方法：在其中点开“引用”文件夹，在"Microsoft.Office.Interop.Word" 上点击鼠标右键，选择“属性”，将属性中的“嵌入互操作类型”的值改为“false”即可
        //  /// </summary>
        //  public void CreateAWord()
        //  {
        //      //实例化word应用对象 
        //      this._wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
        //      Object myNothing = System.Reflection.Missing.Value;
        //      this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
        //  }

        //  /// <summary>
        //  /// 添加页眉 
        //  /// </summary>
        //  /// <param name="pPageHeader"></param>
        //  public void SetPageHeader(string pPageHeader)
        //  {
        //      //添加页眉 
        //      this._wordApplication.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
        //      this._wordApplication.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
        //      this._wordApplication.ActiveWindow.ActivePane.Selection.InsertAfter(pPageHeader);
        //      //设置中间对齐 
        //      this._wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //      //跳出页眉设置 
        //      this._wordApplication.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
        //  }
        //  /// <summary>
        //  /// 插入文字
        //  /// </summary>
        //  /// <param name="pText">文本信息</param>
        //  /// <param name="pFontSize">字体大小</param>
        //  /// <param name="pFontColor">字体颜色</param>
        //  /// <param name="pFontBold">字体粗体</param>
        //  /// <param name="ptextAlignment">方向</param>
        //  public void InsertText(string pText, int pFontSize, Microsoft.Office.Interop.Word.WdColor pFontColor, int pFontBold, Microsoft.Office.Interop.Word.WdParagraphAlignment ptextAlignment)
        //  {
        //      //设置字体样式以及方向 
        //      this._wordApplication.Application.Selection.Font.Size = pFontSize;
        //      this._wordApplication.Application.Selection.Font.Bold = pFontBold;
        //      this._wordApplication.Application.Selection.Font.Color = pFontColor;
        //      this._wordApplication.Application.Selection.ParagraphFormat.Alignment = ptextAlignment;
        //      this._wordApplication.Application.Selection.TypeText(pText);
        //  }
        //  /// <summary>
        //  /// 换行
        //  /// </summary>
        //  public void NewLine()
        //  {
        //      //换行 
        //      this._wordApplication.Application.Selection.TypeParagraph();
        //  }
        //  /// <summary>
        //  /// 插入一个图片 
        //  /// </summary>
        //  /// <param name="pPictureFileName"></param>
        //  public void InsertPicture(string pPictureFileName)
        //  {
        //      object myNothing = System.Reflection.Missing.Value;
        //      //图片居中显示 
        //      this._wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //      this._wordApplication.Application.Selection.InlineShapes.AddPicture(pPictureFileName, ref myNothing, ref myNothing, ref myNothing);
        //  }
        //  /// <summary>
        //  /// 插入表格
        //  /// </summary>
        //  public void InsertTable()
        //  {
        //      object myNothing = System.Reflection.Missing.Value;
        //     Table table1 = _wordDocument.Tables.Add(_wordApplication.Selection.Range, 4, 3, ref myNothing, ref myNothing);
        //      _wordDocument.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";
        //      _wordDocument.Tables[1].Cell(1, 2).Range.Text = "电脑";
        //      _wordDocument.Tables[1].Cell(1, 3).Range.Text = "手机";
        //      _wordDocument.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
        //      _wordDocument.Tables[1].Cell(3, 1).Range.Text = "价格(元)";
        //      _wordDocument.Tables[1].Cell(4, 1).Range.Text = "共同信息";
        //      _wordDocument.Tables[1].Cell(4, 2).Range.Text = "信息A";
        //      _wordDocument.Tables[1].Cell(4, 3).Range.Text = "信息B";
        //      table1.Select();
        //      table1.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中

        //      _wordApplication.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
        //      _wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //      _wordApplication.Selection.Cells.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
        //      _wordApplication.Selection.Cells.Height = 40;
        //      table1.Rows[2].Height = 20;
        //      table1.Rows[3].Height = 20;
        //      table1.Rows[4].Height = 20;
        //      table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //      _wordApplication.Selection.Cells.Width = 150;
        //      table1.Columns[1].Width = 75;
        //      table1.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
        //      table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;


        //      _wordApplication.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
        //      _wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //      _wordApplication.Selection.Cells.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
        //      _wordApplication.Selection.Cells.Height = 40;
        //      table1.Rows[2].Height = 20; table1.Rows[3].Height = 20;
        //      table1.Rows[4].Height = 20;
        //      table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        //      _wordApplication.Selection.Cells.Width = 150;
        //      table1.Columns[1].Width = 75;
        //      table1.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
        //      table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

        //      //表头斜线 
        //      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible = true;
        //      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
        //      table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;


        //      //表格边框             
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Visible = true;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;

        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible = true;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;

        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;

        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy;

        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible = true;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy;

        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;

        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Visible = true;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
        //      table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
        //  }
        //  [DllImport("shell32.dll ")]
        //  public static extern int ShellExecute(IntPtr hwnd, String lpszOp, String lpszFile, String lpszParams, String lpszDir, int FsShowCmd);
        //  /// <summary>
        //  /// 关闭文档 
        //  /// </summary>
        //  public void CloseDocument(string fileName)
        //  {
        //      object myNothing = System.Reflection.Missing.Value;
        //      //关闭文档 
        //      object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; _wordDocument.Close(ref myNothing, ref myNothing, ref myNothing);
        //      _wordApplication.Application.Quit(ref saveOption, ref myNothing, ref myNothing); _wordDocument = null; _wordApplication = null;
             
        //  }
        //  /// <summary>
        //  /// 保存文件 
        //  /// </summary>
        //  /// <param name="pFileName">文件名</param>
        //  public void SaveWord(string pFileName)
        //  {
        //      object myNothing = System.Reflection.Missing.Value;
        //      object myFileName = pFileName;
        //      object myWordFormatDocument = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
        //      object myLockd = false;
        //      object myPassword = "";
        //      object myAddto = true;
        //      try
        //      {
        //          this._wordDocument.SaveAs(ref myFileName, ref myWordFormatDocument, ref myLockd, ref myPassword,
        //              ref myAddto, ref myPassword,
        //              ref myLockd, ref myLockd, ref myLockd, ref myLockd, ref myNothing, ref myNothing, ref myNothing,
        //              ref myNothing, ref myNothing, ref myNothing);
        //      }
        //      catch (Exception exception)
        //      {
        //          throw new Exception("保存word文档失败!");
        //      }
        //  }



    }
}
